package utils

import (
	"fmt"
	"strings"
	"time"
)

type TokenPojo struct {
	Id    string
	Pass  string
	Start time.Time
}

func NewTokenPojo() *TokenPojo {
	return &TokenPojo{}
}

func BuildToken(userid string, pass string) *TokenPojo {
	return &TokenPojo{Id: userid, Pass: pass, Start: time.Now()}
}

func MakeToken(token *TokenPojo, MixKey string) string {
	if token.Start.IsZero() {
		token.Start = time.Now()
	}
	s0 := fmt.Sprintf("%s,%s,%d", token.Id, token.Pass, token.Start.Unix())
	s0 += fmt.Sprintf(",%.2X", CRC([]byte(MD5(s0+MixKey))))
	return EncryptHexString(s0, MixKey)
}

func ExtractToken(tokenstr string, mixKey string, token *TokenPojo) (err error) {
	s0 := DecryptHexString(tokenstr, mixKey)
	if len(s0) == 0 {
		err = fmt.Errorf("非法的TOKEN, 解密失败[%s]", token)
		return
	}

	s1 := string(s0)
	strs := strings.SplitN(s1, ",", 4)
	if len(strs) != 4 {
		err = fmt.Errorf("非法的TOKEN[%s]", token)
		return
	}
	crc0 := fmt.Sprintf("%.2X", CRC([]byte(MD5(s1[:len(s1)-3]+mixKey))))
	if crc0 != strs[3] {
		err = fmt.Errorf("非法的TOKEN[%s]", token)
		return
	}
	token.Id = strs[0]
	token.Pass = strs[1]
	token.Start = time.Unix(StrToInt64Def(strs[2], 0), 0)
	return
}
